import 'package:flutter/material.dart';
import 'package:visibility_detector/visibility_detector.dart';

import '../utils/utils.dart';

class GifWidget extends StatefulWidget {
  const GifWidget({super.key, required this.width, required this.height, required this.asset, required this.duration});

  final double width;
  final double height;
  final String asset;
  final Duration duration;

  @override
  State<GifWidget> createState() => _GifWidgetState();
}

class _GifWidgetState extends State<GifWidget> with TickerProviderStateMixin{
  late final AnimationController _controller = AnimationController(
    duration: widget.duration, vsync: this
  )..repeat();

  @override
  Widget build(BuildContext context) {
    return VisibilityDetector(
      key: Key("${DateTime.now().microsecondsSinceEpoch}"),
      onVisibilityChanged: (VisibilityInfo info) {
        if(!info.visibleBounds.isEmpty && !_controller.isAnimating){
          _controller.repeat();
        }else if(_controller.isAnimating){
          _controller.stop();
        }
      },
      child: AnimatedBuilder(
        animation: _controller,
        builder: (context,child) => Image.asset(
          Utils.getFilePath(widget.asset),
          width: widget.width,height: widget.height,
        )
      ),
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }
}
